<template>
    <div class="index-page">
      <!-- 搜索框模块 -->
      <el-card>
        <el-row>
          <el-col :span="24">
            <el-form :model="form" label-width="100px" v-show="showSearch">
              <el-row :gutter="20">

                <el-col :span="5">
                  <el-form-item label="产品名称" id="name">
                    <el-input
                      placeholder="请输入产品名称"
                      clearable
                      v-model="form.name"
                    >
                    </el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="5">
                  <el-form-item label="产品类别">
                    <el-select
                      value-key="value"
                      clearable
                      v-model="form.category"
                      placeholder="请选择产品类别"
                      @change="handleProductChange"
                    >
                      <el-option
                        v-for="item in productAndDeviceArr"
                        :key="item.value"
                        :label="item.label"
                        :value="item"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="5">
                  <el-form-item label="改造类型">
                    <el-select
                      clearable
                      v-model="form.type"
                      placeholder="请选择改造类型"
                    >
                      <el-option
                        v-for="item in change_type"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="5">
                  <el-form-item label="状态" id="status">
                    <el-select
                      clearable
                      v-model="form.status"
                      placeholder="请选择状态"
                    >
                      <el-option
                        v-for="item in suit_elderly_status"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="4">
                  <el-button type="primary" icon="Search" @click="handleQuery"
                    >搜索</el-button
                  >
                  <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                </el-col>
              </el-row>
            </el-form>
          </el-col>
        </el-row>

        <el-row style="margin-bottom: 10px">
          <el-col :span="5">
            <el-button plain type="primary" icon="Plus" @click="handleAdd"
              >新增</el-button
            >
          </el-col>

          <right-toolbar
            v-model:showSearch="showSearch"
            @queryTable="getList"
          ></right-toolbar>
        </el-row>

        <el-table
          v-loading="loading"
          :data="tableData"
          stripe
          border
          max-height="500"
          :cell-style="{ 'text-align': 'center' }"
          :header-cell-style="{ 'text-align': 'center' }"
        >
          <el-table-column  width="200" label="产品名称">
            <template v-slot:default="scope">
              <span>{{ scope.row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column label="改造类型">
            <template v-slot:default="scope">
              <span>{{ handleType(scope.row.typeId) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            width="200"
            label="产品类别"
          >
          <template v-slot:default="scope">
            <span v-if="scope.row.productCategoryId ? true:false" >{{ handleCategory(scope.row.productCategoryId) }}</span>
            <span v-else>{{ handleDeviceCategory(scope.row.deviceCategoryId) }}</span>
          </template>
        </el-table-column>

          <el-table-column prop="unitPrice" label="单价(元)">
            <template v-slot:default="scope">
              <span>{{ scope.row.unitPrice }}</span>
            </template>
          </el-table-column>

          <el-table-column
            label="状态"
          >
          <template v-slot:default="scope">
            <el-tag :type="scope.row.status === '0' ? '':'danger'">
              <span>{{ handleStatus(scope.row.status) }}</span>
            </el-tag>
          </template>
        </el-table-column>
          <el-table-column
            prop="notes"
            label="备注"
          ></el-table-column>

          <el-table-column label="操作">
            <template v-slot:default="scope">
              <el-button
                icon="Edit"
                type="primary"
                link
                @click="handleEdit(scope.row)"
                >修改</el-button
              >
              <el-button
                icon="Delete"
                type="danger"
                link
                @click="handleDelete(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <!-- 全局分页 -->
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="paginationData.page"
          v-model:limit="paginationData.limit"
          @pagination="getList"
        ></pagination>
      </el-card>

      <!-- 新增编辑弹框 -->
      <el-dialog
        width="50%"
        v-model="dialogShow"
        v-if="dialogShow"
        :title="dialogTitle + '产品'"
        :before-close="closeDialog"
        :close-on-click-modal="false"
      >
        <el-form
          ref="ruleFormRef"
          :model="newForm"
          label-width="120px"
          :rules="rules"
        >
          <el-form-item label="改造类型" prop="type">
            <el-select
              v-model="newForm.type"
              placeholder="请选择改造类型"
              @change="handleTypeChange"
            >
              <el-option
                v-for="item in change_type"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="产品类别" prop="category" v-if="!isIntelligentChange">
            <el-select
              v-model="newForm.category"
              placeholder="请选择产品类别"
              :disabled="isDisable"
              @change="handleCategoryChange"
            >
              <el-option
                v-for="item in product_category"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="产品名称" prop="name" v-if="!isIntelligentChange">
            <el-input
              v-model="newForm.name"
              placeholder="请输入产品名称"
            ></el-input>
          </el-form-item>
          <!-- 设备类别 -->
          <el-form-item label="设备类别" v-if="isIntelligentChange" prop="deviceCategory">
            <el-select
              clearable
              v-model="newForm.deviceCategory"
              placeholder="请选择设备类别"
              @change="handleDeviceCategoryChange"
            >
              <el-option
                v-for="item in deviceTypeArrForIntelligent"
                :key="item.id"
                :label="item.typeName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 设备型号 -->
          <el-form-item label="设备型号" v-if="isIntelligentChange" prop="deviceModelData">
            <el-select
              clearable
              value-key="id"
              v-model="newForm.deviceModelData"
              placeholder="请选择设备型号"
              @change="handleDeviceModelChange"
            >
              <el-option
                v-for="item in deviceModelArr"
                :key="item.id"
                :label="item.deviceModel"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="单价(元)" prop="unitPrice">
            <el-input v-model="newForm.unitPrice" placeholder="请输入单价（例如:30.00)" @change="changePrice" />
          </el-form-item>

          <el-form-item label="状态">
            <el-radio-group v-model="newForm.status">
              <el-radio v-for="item in suit_elderly_status"  :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="备注" prop="notes">
            <el-input type="textarea" v-model="newForm.notes" :autosize="{ minRows: 2, maxRows: 10 }" placeholder="请输入备注" show-word-limit maxlength="500"></el-input>
          </el-form-item>

        </el-form>

        <template v-slot:footer>
          <span class="dialog-footer">
            <el-button type="primary" @click="submit(ruleFormRef)"
            >确定</el-button
            >
            <el-button @click="closeDialog">取消</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </template>

  <script setup>
  import {
    getDeviceModelArr,
    getDeviceTypeArr,
    getSuitElderlyProductData,
    getDeviceTypeData,
    addNewSuitElderlyProductData,
    deleteSuitElderlyProductData,
    editSuitElderlyProductData
  } from "../../../api/suitElderlyProduct/index"
  import { ref, reactive, onMounted, toRefs } from "vue"
  import { ElMessage, ElMessageBox } from "element-plus"
  import formatNumberWithTwoDecimalPlaces from '@/utils/price-validate'

  const { proxy } = getCurrentInstance();
  // 字典-产品类别-改造类型-状态
  const { product_category,change_type,suit_elderly_status,device_name } = proxy.useDict("product_category","change_type","suit_elderly_status","device_name");

  // 字典-指标单位

const isDisable=ref(true)


  // form表单拿到原生dom
  const ruleFormRef = ref();

  // 校验规则
  const rules = ref({
    type: [
      {
        required: true,
        message: "改造类型不能为空",
        trigger: "change",
      },
    ],
    category: [
      {
        required: true,
        message: "产品类别不能为空",
        trigger: "change",
      },
    ],
    name: [
      {
        required: true,
        message: "产品名称不能为空",
        trigger: "blur",
      },
      { min: 1, max: 20, message: "产品名称不超过20个字符", trigger: "blur" }
    ],
    unitPrice: [
      {
        required: true,
        message: "单价不能为空",
        trigger: "blur",
      },
    ],
    notes: [
      { required: false, message: "请输入备注", trigger: "blur" },
      { required: false, min: 1, max:500, message: "备注不超过500个字符", trigger: "blur" }
    ],
    deviceCategory: [
      { required: true, message: "设备类别不能为空", trigger: "change" }
    ],
    deviceModelData: [
      { required: true, message: "设备型号不能为空", trigger: "change" }
    ]
  });

  // 产品类别+设备类型拼接数组
  const productAndDeviceArr=ref([])

  // 智能化改造-设备类型数组
  const deviceTypeArrForIntelligent=ref([])

  // 设备型号的数组
  const deviceModelArr=ref([])

  // 设备类别数据用于表格
  const deviceTypeForTable=ref([])

  // 开关-搜索-是否智能化改造
  const isIntelligentForSearch=ref(false)

  // 弹框表单form数据
  const newForm = ref({
    name: "", // 产品名称
    type: "", // 改造类型
    category: "", //产品类别
    status: "0",
    notes:"",
    unitPrice:"",
    deviceCategory:"", // 设备类别
    deviceCategoryName: "",
    deviceModelData:"", // 设备型号
    networkType: null // 网络类型
  });

  // 编辑要用的id
  const editId = ref("");

  // 是否为智能化改造
  const isIntelligentChange = ref(false)

  // 显示弹框
  const dialogShow = ref(false);
  // 弹框标题
  const dialogTitle = ref("新增");

  const showSearch = ref(true);
  const loading = ref(true);
  // 搜索表单
  const form = reactive({
    name:"",
    category: "",
    type: "",
    status: "",
  });
  // 分页
  const total = ref(0);
  const paginationData = reactive({
    page: 1,
    limit: 10,
  });

  // 表格
  const tableData = ref([]);

  // 拿表格数据
  const getList = () => {
    loading.value = true;
    // 整理查询参数
    const queryData = {
      page: paginationData.page,
      limit: paginationData.limit,

      // category:form.category,
      name:form.name,
      typeId:form.type,
      status:form.status,

      productCategoryId:isIntelligentForSearch.value ? null : form.category.value,
      deviceCategoryId:isIntelligentForSearch.value ? form.category.value : null,
    };

    getSuitElderlyProductData(queryData)
      .then((res) => {
        tableData.value = res.page.list;
        loading.value = false;
        total.value = res.page.totalCount;
        paginationData.page=res.page.currPage
        paginationData.limit=res.page.pageSize
      }).catch((error) => {});
  };

  // 点击搜索按钮
  const handleQuery = () => {
    getList();
  };

  // 点击重置按钮
  const resetQuery = () => {
    form.name = "";
    form.category = "";
    form.status = "";
    form.type = "";
    getList();
  };

  // 点击新增按钮
  const handleAdd = () => {
    dialogShow.value = true;
    dialogTitle.value = "新增";
    // 重新拿到下拉框的数组
  };

  // 关闭弹框
  const closeDialog = () => {
    dialogShow.value = false;
    dialogTitle.value = "";
    // 清空表单的数据
    newForm.value.type = "";
    newForm.value.category = "";
    newForm.value.name = "";
    newForm.value.unitPrice = null;
    newForm.value.status = "0";
    newForm.value.notes = "";
    // 清空智能化数据
    newForm.value.deviceCategory = "",
    newForm.value.deviceModelData = ""
    // 清空下拉数组

    isDisable.value=true
    isIntelligentChange.value=false
    
  };

  // 监听改造类型选中时
  const handleTypeChange = (e) => {
    if(e==="1"){
      // 给智能化改造数据赋值为真
      isIntelligentChange.value=true
      // 设备类别要清空
      newForm.value.deviceCategory=''
      // 设备型号要清空
      newForm.value.deviceModelData=''
      // 选中智能化改造，发请求拿到设备类型数组
      getDeviceTypeArr().then((res)=>{
        deviceTypeArrForIntelligent.value=res.deviceTypeList
      }).catch((error)=>{})
    }else{
      isDisable.value=false
      isIntelligentChange.value=false
      // 产品类别要清空
      newForm.value.category=''
      // 产品名称要清空
      newForm.value.name=''
    }
  };

    // 监听分类选中时
  const handleCategoryChange = (e) => {};

  // 点击弹框的确定按钮
  const submit = (ruleFormRefInstance) => {

    if (!ruleFormRefInstance) {
      return;
    }

    if (dialogTitle.value === "编辑") {
      let editParams = {}
      // 组装参数
      if(isIntelligentChange.value){

        // 是智能化改造
        editParams = {
          id: editId.value,
          typeId: newForm.value.type, // 改造类型
          deviceCategoryId:newForm.value.deviceCategory, // 设备类别
          deviceCategoryName: newForm.value.deviceCategoryName,
          modelId: newForm.value.deviceModelData.id, // 设备型号
          productCategoryId: null,
          name: newForm.value.deviceModelData.deviceModel,
          unitPrice: newForm.value.unitPrice,
          status: newForm.value.status,
          notes: newForm.value.notes,
          networkType: newForm.value.networkType
        };


      } else {
        // 不是智能化改造
        editParams={
          id:editId.value,
          typeId:newForm.value.type,
          productCategoryId:newForm.value.category,
          name:newForm.value.name,
          unitPrice:newForm.value.unitPrice,
          status:newForm.value.status,
          notes:newForm.value.notes,
          deviceCategoryId:null,
          modelId:null,
          networkType: newForm.value.networkType
        }

      }
      console.log(editParams, "<<<=== editParams");

      ruleFormRefInstance.validate((valid) => {
        console.log(valid, "valid-结果");
        if (valid) {
          editSuitElderlyProductData(editParams)
            .then((res) => {
              console.log(res, "<<<=== res 编辑成功");
              // 关闭弹框
              closeDialog();
              getList();
              isIntelligentChange.value=false
            })
            .catch((error) => {
              console.log(error, "<<<=== error");
            });
        } else {
          return false;
        }
      });

      return;
    }
    // 下面是新增---------------------------------------------
    ruleFormRefInstance.validate((valid) => {
      if (valid) {
        let params={}
        // 组装参数-不是智能改造
        if(isIntelligentChange.value){
          // 选中了智能化改造
          // 组装参数-智能化改造
          params={
            typeId:newForm.value.type,//改造类型
            deviceCategoryId:newForm.value.deviceCategory,//设备类别
            deviceCategoryName: newForm.value.deviceCategoryName,
            modelId:newForm.value.deviceModelData.id,//设备型号
            productCategoryId:null,
            name:newForm.value.deviceModelData.deviceModel,
            unitPrice:newForm.value.unitPrice,
            status:newForm.value.status,
            notes:newForm.value.notes,
            networkType: newForm.value.networkType
          }

          console.log(params, "<<<=== params 选中智能化");
        }else{
          console.log(isIntelligentChange.value,"<<<=== 没有选中智能化改造-isIntelligentChange.value")
          // 没有选中智能化
          // 组装参数
          params = {
            typeId:newForm.value.type,
            productCategoryId:newForm.value.category,
            name:newForm.value.name,
            unitPrice:newForm.value.unitPrice,
            status:newForm.value.status,
            notes:newForm.value.notes
          };
          console.log(params, "<<<=== params 没有选中智能化");
        }

        addNewSuitElderlyProductData(params)
          .then((res) => {
            console.log(res, "<<<=== res 新增适老化产品");
            // 关闭弹框
            closeDialog();
            getList();
            isIntelligentChange.value=false
          })
          .catch((error) => {
            console.log(error, "<<<=== error");
          });
      } else {
        return false;
      }
    });
  };

  // 点击修改
  const handleEdit = (data) => {
    dialogShow.value = true;
    dialogTitle.value = "编辑";

    isDisable.value=false

    console.log(data, "<<<=== 点击修改 data 当前这个行的数据");
    // 保存id,编辑提交要用
    editId.value = data.id;
    console.log(editId.value, "<<<=== editId.value");
    // 数据回显
    if(data.typeId==1){
      // 当前行是智能化改造数据
      isIntelligentChange.value=true
      newForm.value.type = data.typeId;
      deviceTypeArrForIntelligent.value=deviceTypeForTable.value
      newForm.value.deviceCategory = Number(data.deviceCategoryId);

      // 设备型号数组

      getDeviceModelArr(data.deviceCategoryId).then((res)=>{
      deviceModelArr.value=res.modelList

      console.log(deviceModelArr.value,"<<<=== deviceModelArr.value 设备型号数据2")

      newForm.value.deviceModelData=res.modelList[0]
    }).catch((error)=>{
      console.log(error,"<<<=== error")
    })

    }else{
      // 普通
      isIntelligentChange.value=false
      newForm.value.type = data.typeId;
      newForm.value.category=data.productCategoryId

    }

    newForm.value.name = data.name;
    newForm.value.unitPrice = data.unitPrice;
    newForm.value.status = data.status;
    newForm.value.notes = data.notes;
  };

  // 点击删除
  const handleDelete = (data) => {
    console.log(data, "<<<=== 点击删除-data");
    ElMessageBox.confirm(`是否确定删除${data.name}`, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        deleteSuitElderlyProductData([data.id])
          .then((res) => {
            console.log(res, "<<<=== res");
            getList();
            ElMessage({
              type: "success",
              message: "删除成功",
            });
          })
          .catch((error) => {
            console.log(error, "<<<=== error");
          });
      })
      .catch((error) => {
        console.log(error, "error");
        ElMessage({
          type: "warning",
          message: "取消删除",
        });
      });
  };

  // 写方法处理改造类型
  const handleType = (data) => {
    return change_type.value.find((item) => {
      return item.value === data;
    })?.label;
  };

    // 写方法处理适老化状态
  const handleStatus = (data) => {
    return suit_elderly_status.value.find((item) => {
      return item.value === data;
    })?.label;
  };

  // 写方法处理产品类别的显示-注意：如果这个函数最后返回的是undefined,undefined在模板上是不显示的
  const handleCategory = (data) => {
    return product_category.value.find((item) => {
      return item.value === data;
    })?.label;
  };

  // 监听设备类别下拉选中触发
  const handleDeviceCategoryChange=(val)=>{
    newForm.value.deviceModel=""
    console.log("【 选中的设备类别 】 = ", val.label)
    // 清空表单绑定的设备型号
    newForm.value.deviceModelData = ""
    newForm.value.deviceCategoryName = val.label
    console.log(deviceModelArr.value,"<<<=== deviceModelArr.value 设备型号数组1")
    // 根据选中的设备类型的值，拿到设备的型号的数据
    getDeviceModelArr(val).then( (res) => {

      deviceModelArr.value = res.modelList
      console.log(deviceModelArr.value,"<<<=== deviceModelArr.value 设备型号数组2")

    }).catch((error)=>{})

  }

  // 监听设备型号的选中触发
  const handleDeviceModelChange=(val)=>{
    console.log(val,"<<<=== val 设备型号选中")
    newForm.value.networkType = val.networkType
  }

  // 页面挂载的时候就拿数据
  onMounted(()=>{

    // 拿设备类型的数据
    getDeviceTypeData().then((res)=>{
      const newArr=res.page.list.concat(product_category.value)
      const resArr=newArr.map((item)=>{
        if(!item.label && !item.value){
          return {label:item.typeName,value:item.id,isIntelligent:true}
        }else{
          return Object.assign(item,{isIntelligent:false})
        }
      })
      console.log(newArr,"<<<=== newArr的数据")
      console.log(resArr,"<<<=== resArr 拼接后的数据")
      productAndDeviceArr.value=resArr
    }).catch((error)=>{})

    // 表格中处理设备类别
    getDeviceTypeArr().then((res)=>{
        deviceTypeForTable.value=res.deviceTypeList
      }).catch((error)=>{})
  })

  // 处理设备类别的方法
  const handleDeviceCategory=(data)=>{
    return deviceTypeForTable.value.find((item)=>{
      return item.id===data
    })?.typeName

  }

  // 搜索监听产品类别下拉选中
  const handleProductChange=(val)=>{
    console.log(val,"<<<=== val 选中产品类别下拉-搜索")
    isIntelligentForSearch.value=val.isIntelligent
    console.log(isIntelligentForSearch.value,"<<<=== isIntelligentForSearch-真假")
  }

  function changePrice (val) {
    if (!(typeof (val - 0) == "number" && !isNaN(val - 0))) {
      proxy.$modal.msgError("请正确输入金额格式");
      newForm.value.unitPrice = "";
      return false
    }

    newForm.value.unitPrice = formatNumberWithTwoDecimalPlaces(newForm.value.unitPrice-0, 2)
  }

  getList();
  </script>

  <style lang="scss" scoped>
  .index-page {
    padding: 20px;
  }

  :deep(.el-form-item[id="name"] .el-form-item__label) {
    // border:1px solid orange;
    width: 70px !important;
  }

  :deep(.el-form-item[id="status"] .el-form-item__label) {
    // border:1px solid orange;
    width: 70px !important;
  }

  .avatar-uploader-icon{
    border-radius: 5px;
    border: 1px dashed #8c939d;
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }

  .avatar-uploader-icon:hover{
    border: 1px dashed #409eff;

  }
  </style>
